#include <string.h>
#include "cJSON/cJSON.h"
#include "log/log.h"
#include "app_common.h"
#include <stdlib.h>
/**
 * @brief 把字符串转换成JSON格式
 *
 * @param chars 代转换的字符串
 * @param len 字符串长度
 * @return char* 转换后的JSON数据
 *
 * 类似：124kkabcd的字符数组
 *abcd->[61626364]
 */
char *app_message_charsToJSON(char *chars, int len)
{
    /*先获取各条数据的长度*/
    int conn_type = chars[0];
    int id_len = chars[1];
    int msg_len = chars[2];
    if (len != 3 + id_len + msg_len)
    {
        log_error("data error!");
        return NULL;
    }
    char id_chars[id_len];
    char msg_chars[msg_len];

    memcpy(id_chars, chars + 3, id_len);
    memcpy(msg_chars, chars + 3 + id_len, msg_len);

    /*使用工具函数，把字符转换成16进制的数据,,chars_to_hex(char* ,int)*/
    char *id_hex = app_common_charsToHex(id_chars, id_len);
    char *msg_hex = app_common_charsToHex(msg_chars, msg_len);

    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "conn_type", conn_type);
    cJSON_AddStringToObject(root, "id", id_hex);
    cJSON_AddStringToObject(root, "msg", msg_hex);

    char *json_str = cJSON_PrintUnformatted(root);
    /*释放json对象*/
    cJSON_Delete(root);
    free(id_hex);
    free(msg_hex);

    return json_str;
}

/**
 * @brief 把JSON格式的字符串转换成char字符数组
 * [61626364]->abcd
 * @param json json格式的字符串
 * @param buffer 缓冲区
 * @param len 缓冲区长度
 * @return int 转换后的字符数组的长度
 */
int app_message_JSONToChars(char *json, char *buffer, int len)
{
    cJSON *root = cJSON_Parse(json);
    /*获取到键值对中的16进制信息*/
    char conn_type = cJSON_GetObjectItem(root, "conn_type")->valueint;
    char *id_hex = cJSON_GetObjectItem(root, "id")->valuestring;
    char *msg_hex = cJSON_GetObjectItem(root, "msg")->valuestring;

    int id_len = -1;
    int msg_len = -1;
    /*使用工具函数把获取的16进制信息转换成字符*/
    char *id_char = app_common_hexToChars(id_hex, &id_len);
    char *msg_char = app_common_hexToChars(msg_hex, &msg_len);

    /*获取后的数据长度大于字符数组缓冲区的长度，错误！*/
    if (len < 3 + id_len + msg_len)
    {
        log_error("buffer is not enough!");
        cJSON_Delete(root);
        return -1;
    }
    /*把转换后的数据依次复制到缓冲区中*/
    buffer[0] = conn_type;
    buffer[1] = id_len;
    buffer[2] = msg_len;
    memcpy(buffer + 3, id_char, id_len);
    memcpy(buffer + 3 + id_len, msg_char, msg_len);
    /*释放JSON对象*/
    cJSON_Delete(root);
    free(id_char);
    free(msg_char);

    return 3 + id_len + msg_len;
}